<?php

namespace App\Exports;

use App\Models\airline\base\FlightModel;
use App\Models\finance\ReceivableGenericModel;
use App\Models\OrderModel;
use Illuminate\Http\Request;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\WithMapping;

class ReceivableGenericExport implements FromCollection, WithHeadings, WithMapping
{
    protected $request;
    protected $dynamicHeadings;
    protected $fieldsToCheck = [
        'air_freight' => '空运费',
        'bill_fee' => '提单费',
        'split_order_fee' => '分单费',
        'print_order_fee' => '打单费',
        'make_order_fee' => '制单费',
        'change_order_fee' => '改单费',
        'gsc_fee' => '广深车',
        'delivery_fee' => '提货费',
        'registration_fee' => '登记费',
        'parking_fee' => '停车费',
        'tunnel_fee' => '隧道费',
        'customs_fee' => '报关费',
        'hk_mainland_fee' => '中港费',
        'customs_operation_fee' => '操作费',
        'continued_fee' => '续页费',
        'inspection_fee' => '报检录单服务费',
        'electric_fee' => '验电费',
        'storage_fee' => '仓租费',
        'overnight_fee' => '压夜费',
        'overtime_fee' => '加班费',
        'cca_fee' => 'CCA费',
        'scan_fee' => '扫描费',
        'dispatch_fee' => '派送费',
        'unloading_fee' => '卸货费',
        'sorting_fee' => '分货费',
        'loading_fee' => '打板费',
        'packing_fee' => '打包费',
        'black_film' => '缠黑膜',
        'box_fee' => '打木箱费',
        'express_fee' => '快递费',
        'pallet_black_film' => '打卡板缠黑膜',
        'special_cargo_fee' => '特殊货物费',
        'other_fee' => '其他费用',
    ];

    public function __construct(Request $request)
    {
        $this->request = $request;
        $this->initializeDynamicHeadings();
    }

    protected function initializeDynamicHeadings()
    {
        // 获取数据
        $data = $this->getCollectionData();
        // 基础字段（总是显示）
        $baseHeadings = [
            'shipment_date' => '出货日期',
            'take_order_sn' => '提单号',
            'goods_attr' => '货物属性',
            'flight_date' => '航班日期',
            'flight_number' => '航班号',
            'customer_name' => '客户名称',
            'origin' => '起运地',
            'destination' => '目的地',
            'package_num' => '件数',
            'gross_weight' => '毛重',
            'volume_weight' => '体积重',
            'charging_weight' => '计费重',
            'air_freight_unit_price' => '空运单价',
        ];

        // 检查哪些字段需要显示
//        $fieldsToShow = [];
//        foreach ($this->fieldsToCheck as $field => $heading) {
//            $hasNonZeroValue = $data->contains(function ($item) use ($field) {
//                return $item->$field > 0;
//            });
//
//            if ($hasNonZeroValue) {
//                $fieldsToShow[$field] = $heading;
//            }
//        }

        // 合并基础字段和动态字段，最后加上总金额
//        $this->dynamicHeadings = array_merge($baseHeadings, $fieldsToShow, ['total_amount' => '总金额']);
        $this->dynamicHeadings = $baseHeadings;
    }

    protected function getCollectionData()
    {
        $query = ReceivableGenericModel::with(['take_order', 'flight', 'customer', 'create_admin']);
        
        // 筛选条件
        if ($this->request->filled('take_order_sn')) {
            $request_sn = $this->request->input('take_order_sn');
            $query->whereHas('take_order', function($query) use ($request_sn) {
                $query->where('sn', $request_sn);
            });
        }
        
        if ($this->request->filled('flight_id')) {
            $query->where('flight_id', $this->request->input('flight_id'));
        }
        
        if ($this->request->filled('customer_id')) {
            $query->where('customer_id', $this->request->input('customer_id'));
        }
        
        if ($this->request->filled('status')) {
            $query->where('status', $this->request->input('status'));
        }
        
        if ($this->request->filled('origin')) {
            $query->where('origin', 'like', '%' . $this->request->input('origin') . '%');
        }
        
        if ($this->request->filled('destination')) {
            $query->where('destination', 'like', '%' . $this->request->input('destination') . '%');
        }
        
        if ($this->request->filled('flight_time_start') && $this->request->filled('flight_time_end')) {
            $query->whereBetween('flight_date', [$this->request->input('flight_time_start'), $this->request->input('flight_time_end')]);
        }

        return $query->orderBy('id', 'desc')->get();
    }

    public function collection()
    {
        return $this->getCollectionData();
    }

    public function headings(): array
    {
        return array_values($this->dynamicHeadings);
    }

    public function map($item): array
    {
        $origin = $item->flight?->start_port_code ?? '';
        $destination = $item->flight?->arrive_port_code ?? '';

        $flight_date = $item->flight ? date('Y-m-d', strtotime($item->flight->take_off_time)) : '';

        $flight_number_id = $item->flight?->items?->first()->airline_flight_id ?? '';
        $flight_number = FlightModel::where('id', $flight_number_id)->value('flight_number');
        $flight_number = $flight_number ?? '';



        // 构建完整的数据映射
        $fullData = [
            'shipment_date' => $item->take_order->shipment_date ?? '',
            'take_order_sn' => $item->take_order?->sn ?? '',
            'goods_attr' => OrderModel::GOODS_ATTR_MAPS[$item->take_order?->goods_attr ??  ''] ?? '',
            'flight_date' => $flight_date,
            'flight_number' => $flight_number,
            'customer_name' => $item->customer?->name ?? '',
            'origin' => $origin,
            'destination' => $destination,
            'package_num' => $item->package_num,
            'gross_weight' => $item->gross_weight,
            'volume_weight' => $item->volume_weight,
            'charging_weight' => $item->charging_weight,
            'air_freight_unit_price' => $item->air_freight_unit_price,
//            'air_freight' => $item->air_freight,
//            'bill_fee' => $item->bill_fee,
//            'delivery_fee' => $item->delivery_fee,
//            'registration_fee' => $item->registration_fee,
//            'parking_fee' => $item->parking_fee,
//            'tunnel_fee' => $item->tunnel_fee,
//            'customs_fee' => $item->customs_fee,
//            'hk_mainland_fee' => $item->hk_mainland_fee,
//            'customs_operation_fee' => $item->customs_operation_fee,
//            'unloading_fee' => $item->unloading_fee,
//            'packing_fee' => $item->packing_fee,
//            'black_film' => $item->black_film,
//            'pallet_black_film' => $item->pallet_black_film,
//            'special_cargo_fee' => $item->special_cargo_fee,
//            'total_amount' => $item->total_amount,
//            'print_order_fee' => $item->print_order_fee,
//            'split_order_fee' => $item->split_order_fee,
//            'make_order_fee' => $item->make_order_fee,
//            'change_order_fee' => $item->change_order_fee,
//            'gsc_fee' => $item->gsc_fee,
//            'box_fee' => $item->box_fee,
//            'express_fee' => $item->express_fee,
//            'continued_fee' => $item->continued_fee,
//            'inspection_fee' => $item->inspection_fee,
//            'electric_fee' => $item->electric_fee,
//            'storage_fee' => $item->storage_fee,
//            'overnight_fee' => $item->overnight_fee,
//            'overtime_fee' => $item->overtime_fee,
//            'cca_fee' => $item->cca_fee,
//            'scan_fee' => $item->scan_fee,
//            'dispatch_fee' => $item->dispatch_fee,
//            'sorting_fee' => $item->sorting_fee,
//            'loading_fee' => $item->loading_fee,
//            'other_fee' => $item->other_fee,
//            'total_fee' => $item->total_fee,
        ];

        // 只返回需要显示的字段
        $result = [];
        foreach (array_keys($this->dynamicHeadings) as $field) {
            $result[] = $fullData[$field] ?? '';
        }

        return $result;
    }
} 